package com.learn.mail.service;

import com.learn.mail.enums.MailTemplateType;
import jakarta.annotation.Resource;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;
import lombok.extern.slf4j.Slf4j;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class SendEmailServiceImpl implements SendEmailService {


    @Resource
    private JavaMailSender mailSender;

    @Resource
    public GroupTemplate beetlTemplate;

    @Value("${spring.mail.username}")
    private String from;

    private static final int MAX_RETRY = 3;

    @Override
    public void sendTemplateMail(String to, String subject, String templatePath, Map<String, Object> model) throws Exception {
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

        // 设置基本参数
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setFrom(new InternetAddress("li_congzhi0528@163.com", "李某某")); // 发件人地址

        // 渲染模板
        Template template = beetlTemplate.getTemplate(templatePath);
        template.binding(model);
        String html = template.render();

        helper.setText(html, true); // true 表示 HTML

        // 发送
        mailSender.send(message);
    }

    @Override
    public void sendWithAttachment(String to, String subject, String content, File file) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            helper.addAttachment(file.getName(), file);
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            log.error("发送带附件邮件失败", e);
        }
    }

    @Async
    @Override
    public void sendHtmlMailAsync(String to, String subject, MailTemplateType templateType, Map<String, Object> params) {
        if (from.equalsIgnoreCase(to)) {
            throw new IllegalArgumentException("收件人和发件人不能相同");
        }
        for (int i = 1; i <= MAX_RETRY; i++) {
            try {
                String content = renderTemplate(templateType.getTemplate(), params);
                System.out.println(content);
                MimeMessage message = mailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

                helper.setFrom(from);
                helper.setTo(to);
                helper.setSubject(subject);
                helper.setText(content, true);

                mailSender.send(message);
                log.info("第 {} 次发送成功 -> {}", i, to);
                break;
            } catch (Exception e) {
                log.warn("第 {} 次邮件发送失败: {}", i, e.getMessage());
                if (i == MAX_RETRY) {
                    throw new RuntimeException("邮件发送失败重试上限", e);
                }
            }
        }
    }

    @Override
    public void sendBatchEmails(List<String> toList, String subject, String template, Map<String, Object> params) {
        toList.forEach(to -> {
            try {
                sendMail(to, subject, template, params);
            } catch (Exception e) {
                log.error("邮件发送失败: {}", to, e);
            }
        });
    }

    private void sendMail(String to, String subject, String templateName, Map<String, Object> params) throws IOException, MessagingException {
        if (from.equalsIgnoreCase(to)) {
            log.warn("收件人不能与发件人相同: {}", to);
            return;
        }
        Template template = beetlTemplate.getTemplate(templateName);
        template.binding(params);
        String content = template.render();

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(from);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(content, true);

        mailSender.send(message);
    }

    private String renderTemplate(String templateName, Map<String, Object> params) throws IOException {
        Template tpl = beetlTemplate.getTemplate(templateName);
        tpl.binding(params);
        return tpl.render();
    }
}
